<template>
  <div class="history-page">
    <van-nav-bar
      title="浏览历史"
      left-text="返回"
      left-arrow
      right-text="清空"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    
    <div class="history-content">
      <template v-if="historyList.length > 0">
        <div class="history-date" v-for="(group, date) in groupedHistory" :key="date">
          <div class="date-header">{{ formatDate(date) }}</div>
          <div class="history-items">
            <div 
              v-for="(item, index) in group" 
              :key="index" 
              class="history-item"
              @click="navigateTo(item.path)"
            >
              <div class="item-icon">
                <van-icon :name="getIconByType(item.type)" size="20" />
              </div>
              <div class="item-content">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-time">{{ formatTime(item.timestamp) }}</div>
              </div>
              <div class="item-action">
                <van-icon name="delete-o" @click.stop="removeHistoryItem(item.id)" />
              </div>
            </div>
          </div>
        </div>
      </template>
      <div v-else class="empty-state">
        <van-empty description="暂无浏览记录" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'

const router = useRouter()

// 模拟浏览历史数据
const historyList = ref([
  {
    id: 1,
    title: '如何提高Vue3开发效率',
    type: 'article',
    path: '/blog/1',
    timestamp: Date.now() - 1000 * 60 * 30, // 30分钟前
    date: new Date().toISOString().split('T')[0]
  },
  {
    id: 2,
    title: '北京天气预报',
    type: 'weather',
    path: '/weather/beijing',
    timestamp: Date.now() - 1000 * 60 * 60 * 2, // 2小时前
    date: new Date().toISOString().split('T')[0]
  },
  {
    id: 3,
    title: 'TypeScript入门指南',
    type: 'article',
    path: '/blog/2',
    timestamp: Date.now() - 1000 * 60 * 60 * 5, // 5小时前
    date: new Date().toISOString().split('T')[0]
  },
  {
    id: 4,
    title: 'Vue3组件化开发实战',
    type: 'video',
    path: '/video/1',
    timestamp: Date.now() - 1000 * 60 * 60 * 24, // 1天前
    date: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString().split('T')[0]
  },
  {
    id: 5,
    title: '上海天气预报',
    type: 'weather',
    path: '/weather/shanghai',
    timestamp: Date.now() - 1000 * 60 * 60 * 24 * 2, // 2天前
    date: new Date(Date.now() - 1000 * 60 * 60 * 24 * 2).toISOString().split('T')[0]
  }
])

// 按日期分组
const groupedHistory = computed(() => {
  const groups = {}
  
  historyList.value.forEach(item => {
    if (!groups[item.date]) {
      groups[item.date] = []
    }
    groups[item.date].push(item)
  })
  
  // 对每个组内的项目按时间戳排序（从新到旧）
  Object.keys(groups).forEach(date => {
    groups[date].sort((a, b) => b.timestamp - a.timestamp)
  })
  
  return groups
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 清空历史记录
const onClickRight = () => {
  showDialog({
    title: '清空历史记录',
    message: '确定要清空所有浏览历史吗？',
    showCancelButton: true
  }).then(() => {
    historyList.value = []
    showToast('历史记录已清空')
  }).catch(() => {
    // 取消操作
  })
}

// 删除单个历史记录
const removeHistoryItem = (id) => {
  const index = historyList.value.findIndex(item => item.id === id)
  if (index !== -1) {
    historyList.value.splice(index, 1)
    showToast('已删除')
  }
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 根据类型获取图标
const getIconByType = (type) => {
  const iconMap = {
    article: 'notes-o',
    video: 'video-o',
    weather: 'sunny-o',
    search: 'search',
    default: 'browsing-history-o'
  }
  
  return iconMap[type] || iconMap.default
}

// 格式化日期
const formatDate = (dateStr) => {
  const today = new Date().toISOString().split('T')[0]
  const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString().split('T')[0]
  
  if (dateStr === today) {
    return '今天'
  } else if (dateStr === yesterday) {
    return '昨天'
  } else {
    return dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, '$1年$2月$3日')
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${hours}:${minutes}`
}
</script>

<style lang="scss" scoped>
.history-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 20px);
  
  .history-content {
    padding: 12px;
    
    .history-date {
      margin-bottom: 16px;
      
      .date-header {
        font-size: 14px;
        font-weight: 500;
        color: var(--text-color-secondary);
        padding: 8px 0;
      }
      
      .history-items {
        background-color: var(--background-color-light);
        border-radius: 8px;
        overflow: hidden;
        box-shadow: var(--box-shadow);
        
        .history-item {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          border-bottom: 1px solid var(--border-color-light);
          
          &:last-child {
            border-bottom: none;
          }
          
          .item-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background-color: rgba(var(--primary-color-rgb), 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-color);
            margin-right: 12px;
          }
          
          .item-content {
            flex: 1;
            
            .item-title {
              font-size: 16px;
              color: var(--text-color);
              margin-bottom: 4px;
              line-height: 1.4;
            }
            
            .item-time {
              font-size: 12px;
              color: var(--text-color-tertiary);
            }
          }
          
          .item-action {
            padding: 8px;
            color: var(--text-color-tertiary);
          }
        }
      }
    }
  }
  
  .empty-state {
    padding: 60px 0;
  }
}
</style> 